<template>
    <div>
        <el-header style="line-height:40px;" height="40px">
            <el-button type="primary" size="mini" icon="el-icon-circle-plus" @click="addSome">增加同级</el-button>
            <el-button type="primary" size="mini" icon="el-icon-circle-plus" @click="addSon">增加子级</el-button>
        </el-header>
        <el-main>
            <el-table
                :data="tableData"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id" border
                size="mini" :stripe="true"
                height="calc(100vh - 100px)"
				highlight-current-row
                @row-click="rowClickTable"
				:row-class-name="tableRowClassName"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column label="序" type="index" sortable align="center"></el-table-column>
                <el-table-column prop="name" label="部门名称" sortable width="180" header-align="center"  :show-overflow-tooltip="true">
                    <template #default="{row}">
                        <i :class="row.children?'el-icon-folder-opened':'el-icon-document'"></i>
                        {{row.name}}
                    </template>
                </el-table-column>
                <el-table-column prop="staff" label="负责人" sortable width="120"></el-table-column>
                <el-table-column prop="phone" label="电话" min-width="120" align="center"></el-table-column>
                <el-table-column prop="unit" label="所属单位" min-width="120" header-align="center"  :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="desc" label="备注" min-width="180" header-align="center"  :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="操作" min-width="180" align="center">
                    <template #default="{row}">
                        <el-button type="warning" size="mini" icon="el-icon-edit" @click="editData(row)">修改</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteData(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-dialog :title="dialogTitle" :visible.sync="formDialog" :close-on-click-modal="false" width="500px">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" size="mini">
                <el-form-item label="部门编号" prop="number">
                    <el-input v-model="ruleForm.number"></el-input>
                </el-form-item>
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="所属单位" prop="unit">
                    <el-input v-model="ruleForm.unit"></el-input>
                </el-form-item>
                <el-form-item label="负责人" prop="staff">
                    <el-input v-model="ruleForm.staff"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="ruleForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="desc">
                    <el-input type="textarea" v-model="ruleForm.desc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="resetForm('ruleForm')">取 消</el-button>
                <el-button size="mini" type="primary" @click="savaBtn">确 定</el-button>
            </div>
            </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        // 自定义校验规则 验证手机号
        let checkMobile = (rule, value, cb) => {
            // 验证手机号的正则表达式
            const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if (regMobile.test(value)) return cb()
            cb(new Error('请输入合法的手机号'))
        }
        return {
            tableData: [],
            tableInfo:{},
            formDialog: false,
            dialogTitle:'',
            ruleForm: {
                name: 'ce2s',
                phone: '17674656046',
                desc: '2313',
                staff: '23213',
                unit: '23131',
                number: '2313',
            },
            rules: {
                number: [
                    { required: true, message: '请输入部门编号', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入部门名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                staff: [
                    { required: true, message: '请输入负责人', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
            },
            typeBtn:'',
        }
    },
    created () {

    },
    mounted () {
        this.initData()
    },
    methods: {
        // 初始化
        initData(){this.tableData =  JSON.parse(localStorage.getItem('tableData')||'[]')},
        // 选中的table
        rowClickTable(val){ this.tableInfo = val },
        // 递归查询所属层级
        ifThisData(id,list,type){
            for (let i = 0; i < list.length; i++) {
                if (list[i].id==id) {
                    // console.log(id,list,type,i);
                    this.typeInfo(list,type,i)
                    return true
                }
                if(list[i].children) this.ifThisData(id,list[i].children,type,i)
            }
        },
        // 按条件执行
        typeInfo(list,type,index){
            let tool = {
                addSome:()=>list.push({id: this.mathRandom() ,...this.ruleForm}),
                addSon:()=> {
                    if(!list[index].children)list[index].children = []
                    list[index].children.push({...{ id: this.mathRandom(), },...this.ruleForm})
                },
                editData:()=>list[index] = this.ruleForm,
                deleteData:()=>list.splice(index,1),
            }
            tool[type]()
        },
        // 取消 
        resetForm(formName) {
            this.formDialog = false
            this.$refs[formName].resetFields();
        },
        // 保存 formDialog
        savaBtn(){
            this.$refs.ruleForm.validate(valid => {
                if (!valid) return
                JSON.stringify(this.tableData)=='[]'?this.tableData.push({...{ id: this.mathRandom(), },...this.ruleForm}):this.ifThisData(this.tableInfo.id,this.tableData,this.typeBtn)
                localStorage.setItem('tableData',JSON.stringify(this.tableData))
                this.initData()
                this.formDialog = false
            })
        },
        // 添加同级
        addSome(){
            if (JSON.stringify(this.tableInfo)=='{}'&&JSON.stringify(this.tableData)!='[]') return this.$message.error({ showClose: true, message: '请先选择一条数据' })
            this.dialogTitle = '添加同级'
            this.typeBtn = 'addSome'
            this.formDialog = true
        },
        // 添加子级
        addSon(){
            if (JSON.stringify(this.tableInfo)=='{}') return this.$message.error({ showClose: true, message: '请先选择一条数据' })
            this.dialogTitle = '添加子级'
            this.typeBtn = 'addSon'
            this.formDialog = true
        },
        // 修改
        editData(row){
            this.ruleForm = row
            this.dialogTitle = '修改数据'
            this.typeBtn = 'editData'
            this.formDialog = true
        },
        // 删除
        async deleteData(row){ 
            const confirmRsults = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmRsults !== 'confirm') return this.$message.info({ showClose: true, message: '已取消删除' })
            this.ifThisData(row.id,this.tableData,'deleteData') 
            localStorage.setItem('tableData',JSON.stringify(this.tableData))
            this.initData()
        },
        // 生成随机id
        mathRandom(){
            let num = Math.ceil(Math.random()*100000);
            if(this.ifThisId(this.tableData,num))return this.mathRandom()
            return num 
        },
        // 递归查询id是否重复
        ifThisId(list,id){
            for (let i = 0; i < list.length; i++) {
                if (list[i].id==id) return true
                if(list[i].children) this.ifThisData(id,list[i].children)
            }
        },
		//1.3 选中行样式
		tableRowClassName({ row }) { return row.id == this.id ? 'selected-row' : 'un-selected-row'; },
    }
}
</script>

<style scoped lang="less">
/*滚动条*/
/deep/.el-main {
    ::-webkit-scrollbar{ width: 5px; height: 10px; }
    ::-webkit-scrollbar-track{ background-color: rgb(243, 231, 231); }
    ::-webkit-scrollbar-thumb{ border-radius: 3px; background-color: #409EFF; box-shadow: inset 0 0 5px #ddd; }
    ::-webkit-scrollbar-button{ height: 0; background-color: #0099ff; }
    .el-table .cell {
        padding:0 5px;
    }
    .el-table tr.current-row>td, 
    .el-table tr.current-row:hover>td, 
    .el-table tr.selected-row>td, 
    .el-table tr.selected-row.hover-row>td, 
    .el-table tr.selected-row:hover>td {
        background-color: #fff18db8; 
    }
    [class*=" el-icon-"], [class^=el-icon-] {
        color: #72affa;
        font-size: 16px;
    }
}
</style>
